﻿using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections;
using System.Xml.Linq;
using UnityEngine;
using UnityEngine.UI;

public class ApplyUserPanel : AppUI
{
    public GameObject panelObj;

    public UserInfoItem userInfoItem;

    public GameObject applyResultObj;
    public Image resultIcon;
    public Text resultText;
    public GameObject maskObj;
    public Text reasonText;

    public GameObject leaveMsgObj;
    public Text leavMsg;

    public GameObject viewObj;
    public Image viewIcon;
    public Text viewText;

    public Text applyText;
    public Text priceText;

    public Text applyTimeText;
    public Text viewTimeText;
    public Text resultTimeText;

    public GameObject applyBtnObj;
    public Text applyBtnText;

    public GameObject receiveBtnsObj;
    public GameObject chatBtnObj;

    public Sprite goodSpr;
    public Sprite badSpr;

    public Color activeColor = Color.black;
    public Color disActiveColor = Color.black;
    public Color rejectColor = Color.black;

    Apply m_Data;
    public void Init(Apply apply)
    {
        m_Data = apply;

        panelObj.gameObject.SetActive(false);

        InitApplyUI();

        long opponentUserId = m_Data.sourceUserId == MGame.instance.MUser.id ? m_Data.targetUserId : m_Data.sourceUserId;
        RequestServerController.instance.RequestUserInfo(opponentUserId, UpdateUserUI);
    }

    private void UpdateUserUI(UserInfo info)
    {
        panelObj.gameObject.SetActive(true);

        userInfoItem.Init(info);
    }

    void InitApplyUI()
    {
        bool myApply = m_Data.targetUserId != MGame.instance.MUser.id;
        if (myApply)
        {
            InitMyApply();
        }
        else
        {
            InitApplyRecieved();
        }
    }

    void InitMyApply()
    {
        leaveMsgObj.gameObject.SetActive(true);
        maskObj.gameObject.SetActive(false);
        chatBtnObj.SetActive(false);
        reasonText.text = "";

        applyTimeText.text = GetDateTimeStrWithTimestamp(m_Data.applyTime);

        if (m_Data.viewTime > 0)
        {
            viewTimeText.gameObject.SetActive(true);
            viewTimeText.text = GetDateTimeStrWithTimestamp(m_Data.viewTime);
        }
        else
        {
            viewTimeText.gameObject.SetActive(false);
        }
        if (m_Data.result == Apply.Applying)
        {
            applyResultObj.gameObject.SetActive(false);

            viewText.text = "等待对方查看";
            viewText.color = activeColor;
            applyBtnObj.gameObject.SetActive(false);
        }
        else
        {
            resultTimeText.text = GetDateTimeStrWithTimestamp(m_Data.resultTime);

            viewText.color = disActiveColor;
            applyResultObj.gameObject.SetActive(true);

            if (m_Data.result == Apply.ApplyResult_Suc)
            {
                resultIcon.sprite = goodSpr;
                applyBtnObj.gameObject.SetActive(false);
                chatBtnObj.SetActive(true);
                resultText.text = "对方已同意申请";
                resultText.color = activeColor;

            }
            else if (m_Data.result == Apply.ApplyResult_Fail)
            {
                resultIcon.sprite = badSpr;
                applyBtnObj.gameObject.SetActive(true);
                applyBtnText.text = "再次申请";
                resultText.text = "对方已拒绝申请";
                resultText.color = rejectColor;
                reasonText.text = m_Data.rejectMsg;
                maskObj.gameObject.SetActive(true);
            }
        }

        leavMsg.text = m_Data.msg;
        viewObj.gameObject.SetActive(true);
        applyText.text = "发出申请";
        int price = 100;
        priceText.text = $"消耗{price}金币";
        receiveBtnsObj.SetActive(false);
    }
    
    void InitApplyRecieved()
    {
        leaveMsgObj.gameObject.SetActive(true);
        chatBtnObj.SetActive(false);

        leavMsg.text = m_Data.msg;
        viewObj.gameObject.SetActive(false);
        applyText.text = "收到申请";
        priceText.gameObject.SetActive(false);
        maskObj.gameObject.SetActive(false);
        applyBtnObj.gameObject.SetActive(false);

        applyTimeText.text = GetDateTimeStrWithTimestamp(m_Data.applyTime);

        if (m_Data.viewTime <= 0)
        {
            RequestServerController.instance.ReqViewApply(m_Data, (data) => {

                if (data != null)
                {
                    m_Data = data;
                    viewTimeText.text = GetDateTimeStrWithTimestamp(m_Data.viewTime);
                }
                else
                {
                    GameDebug.LogError($"data is null");
                }
            });
        }
        if (m_Data.result == Apply.Applying)
        {
            receiveBtnsObj.SetActive(true);
            applyResultObj.gameObject.SetActive(false);
        }
        else
        {
            receiveBtnsObj.SetActive(false);
            applyResultObj.gameObject.SetActive(true);

            resultTimeText.text = GetDateTimeStrWithTimestamp(m_Data.resultTime);

            if (m_Data.result == Apply.ApplyResult_Suc)
            {
                resultIcon.sprite = goodSpr;
                chatBtnObj.SetActive(true);
                resultText.text = "已接受";
                applyBtnObj.gameObject.SetActive(false);
                resultText.color = activeColor;
            }
            else
            {
                resultIcon.sprite = badSpr;
                resultText.text = "已拒绝";
                resultText.color = rejectColor;
                //applyBtnText.text = "申请认识";
                //applyBtnObj.gameObject.SetActive(true);
                reasonText.text = m_Data.rejectMsg;
            }
        }
    }

    public static string GetDateTimeStrWithTimestamp(long timestamp)
    {
        DateTime dateTime = UnityFunctions.GetTimeZoneDateTime(timestamp);// DateTimeOffset.FromUnixTimeSeconds(timestamp).DateTime;
        return dateTime.ToString("yyyy-MM-dd HH:mm");
    }


    public void OnClickShowUserDetail()
    {
        GameDebug.Log($"OnClickShowUserDetail");
    }

    public void OnClickUserMoment()
    {
        GameDebug.Log($"OnClickUserMoment");
    }

    public void OnClickAccept()
    {
        GameDebug.Log($"OnClickAccept:{m_Data.sourceUserId}");

        m_Data.result = Apply.ApplyResult_Suc;
        m_Data.resultTime = UnityFunctions.GetTimeStampSeconds();
        RequestServerController.instance.ReqUpdateApply(m_Data, (data) =>
        {
            long opponentUserId = m_Data.sourceUserId == MGame.instance.MUser.id ? m_Data.targetUserId : m_Data.sourceUserId;
            RequestServerController.instance.ReqSendDialogue(MGame.instance.MUser.id, opponentUserId, "你好，很高兴认识你~", 
                (dia) =>
            {
                InitApplyUI();
            });
        });
    }

    public void OnClickReject()
    {
        GameDebug.Log($"OnClickReject");
        m_Data.result = Apply.ApplyResult_Fail;
        m_Data.resultTime = UnityFunctions.GetTimeStampSeconds();
        RequestServerController.instance.ReqUpdateApply(m_Data,(data)=>
        {
            InitApplyUI();
        });
        
    }

    public void OnClickApplyAgain()
    {
        //MGame.instance.MUser.UpdateApply(m_Data);
        long targetUserId = m_Data.targetUserId == MGame.instance.MUser.id ? m_Data.sourceUserId : m_Data.targetUserId;
        m_Data = MGame.instance.MUser.AddApply(MGame.instance.MUser.id, targetUserId, Apply.Applying, "你好，想认识你一下~", "", UnityFunctions.GetTimeStampSeconds());
        m_Data.applyTime = UnityFunctions.GetTimeStampSeconds();

        RequestServerController.instance.ReqUpdateApply(m_Data,(data)=> {

            InitApplyUI();
        });
    }

    public void OnClickChat()
    {
        ChatPanel view = this.GetComponentInParent<UIController>().ShowUI<ChatPanel>();

        long mUser = MGame.instance.MUser.id;
        long opponentUserId = m_Data.targetUserId == MGame.instance.MUser.id ? m_Data.sourceUserId : m_Data.targetUserId;

        GameDebug.Log($"OnClickChat:{opponentUserId}");

        RequestServerController.instance.RequestUserInfo(opponentUserId, (targetuserInfo) =>
        {
            var myChat = MGame.instance.MUser.chats.Find(e => e.userId1 == mUser && e.userId2 == opponentUserId);
            var opponentChat = MGame.instance.MUser.chats.Find(e => e.userId1 == opponentUserId && e.userId2 == mUser);
            ChatData chatData = new ChatData()
            {
                myUserId = mUser,
                opponentUserId = opponentUserId,
                myChat = myChat,
                opponentChat = opponentChat,
            };
            view.Init(targetuserInfo, chatData);
        });
    }

    public void GoBack()
    {
        UIController.ShowUI<MainPanel>();
    }
}
